const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const co = require('co');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

const DB = require('./db');
const DT = require('./lib/dt');
const EJS = require('./lib/ejs');
const index = require('./routes/index');
const wall = require('./routes/wall');
const tree = require('./routes/tree');
const person = require('./routes/person');
const calendar = require('./routes/calendar');

const app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.locals.DT = DT;
app.locals.EJS = EJS;

app.use('*', function (req, res, next) {
    co(function* () {
        req.int = function(key, def) {
            try {
                return parseInt(req.params[key] || req.query[key] || req.body[key] || 0);
            } catch (e) {
                return def || 0;
            }
        };
        let today = DT.today;
        const date = new Date();
        const gong = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
        if (!today || today.gong !== gong) {
            today = yield DB.Calendar.findOne({
                raw: true,
                where: {
                    gong: gong,
                }
            });
            const arrG = today.gong.split('-');
            today.gongY = parseInt(arrG[0]);
            today.gongM = parseInt(arrG[1]);
            today.gongD = parseInt(arrG[2]);
            today.gongW = DT.getWeek(today.gong, date.getDay());
            const arrN = today.nong.split('-');
            today.nongY = parseInt(arrN[0]);
            today.nongM = parseInt(arrN[1]);
            today.nongD = parseInt(arrN[2]);
            DT.today = today;
            console.log('今天是：', JSON.stringify(today));
        }
        next();
    }).catch((err) => {
        next(err);
    })
});

app.use('/', index);
app.use('/wall', wall);
app.use('/tree', tree);
app.use('/person', person);
app.use('/calendar', calendar);

app.use(function (req, res, next) {
    res.status(404).send('404 Not Found')
});

app.use(function (err, req, res, next) {
    console.log(err);
    res.status(500).send('500 Server Error')
});

module.exports = app;
